<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var threeSumClosest = function (nums, target) {
      let len = nums.length;
      nums.sort((a, b) => a - b);
      let res = nums[0] + nums[1] + nums[len - 1];
      for (let i = 0; i < len - 2; i++) {
        if (i > 0 && nums[i] === nums[i - 1]) {
          continue;
        }
        let l = i + 1;
        let r = len - 1;
        while (l < r) {
          const sum = nums[i] + nums[l] + nums[r];
          if (sum === target) {
            return target;
          }
          sum > target ? r-- : l++;
          if (Math.abs(sum - target) < Math.abs(res - target)) {
            res = sum;
          }
        }
      }
      return res;
    };
    console.log(threeSumClosest([-1, 2, 1, -4], 1))
  </script>
</body>

</html>